<?php
require_once 'lucene/Custom_Search_Lucene_Document.php';

class SearchIndexer {
    
    protected static $_baseDirecotry;
    protected static $_indexDirctory;
    
    public static function observerTableRow($event, $row) {
        switch($event) {
            case 'post-insert':
                $doc = self::getDocument($row);
                if ($doc !== false) {
                    self::_addToIndex($doc);
                }
                break;
        }
    }
    
    
    public static function getDocument($class, $row) {
        if (method_exists($class, '_getSearchIndexFields')) {
            $fields = array();
            if ($class == 'Book') {
                $fields = Book::_getSearchIndexFields($row);
                $doc = new Custom_Search_Lucene_Document(
                    $fields[Custom_Search_Lucene_Document::CLASS_NAME], 
                    $fields[Custom_Search_Lucene_Document::KEY],
                    $fields[Constant::BOOK_OBJ]
                    );
            }
            return $doc;
        }
        return false;
    }
    
    public static function setBaseDirectory($dir) {
        self::$_baseDirecotry = $dir;
    }
    
    public static function setIndexDirctory($subDir) {
        self::$_indexDirctory = self::$_baseDirecotry.'/'.$subDir;
    }
    
    public static function getIndexDirectory() {
        return self::$_indexDirctory;
    }
    
    public static function _addToIndex($index, $doc) {
        
        $index->addDocument($doc);
        $index->commit();
        $index->optimize();
    }
}

?>